﻿
/**
 * 定义模型类型。
 */
Ext.define('Happy.metadata.template.DefineModel', {
    alias: 'template.define-model',
    requires: [
        'Happy.data.Model',
        'Happy.data.TreeModel'
    ],

    /**
     * 执行运行时代码生成。
     * 
     * @param {Happy.metadata.ClassGenerator} generator
     * @param {Happy.metadata.Metadata} metadata
     */
    generate: function (generator, metadata) {
        var me = this;

        me.defineModel(generator, metadata);
        if (metadata.isTree()) {
            me.defineTreeModel(generator, metadata);
        }
    },

    /**
     * 定义模型类型。
     * 
     * @private
     * @param {Happy.metadata.ClassGenerator} generator
     * @param {Happy.metadata.Metadata} metadata
     */
    defineModel: function (generator, metadata) {
        var classConfig = {
            extend: metadata.isTree() ? 'Happy.data.TreeModel' : 'Happy.data.Model',

            metadata: metadata,

            idProperty: 'Id',
            fields: metadata.getDefaultModelFields(),
            relation: metadata.getDefaultModelRelationConfig(),
            proxy: metadata.getDefaultProxyConfig()
        };
        Ext.merge(classConfig, metadata.data.model || {});
        Ext.define(metadata.getModelClassName(), classConfig);
    },

    /**
     * 定义树形模型类型。
     * 
     * @private
     * @param {Happy.metadata.ClassGenerator} generator
     * @param {Happy.metadata.Metadata} metadata
     */
    defineTreeModel: function (generator, metadata) {
        var classConfig = {
            extend: metadata.isTree() ? 'Happy.data.TreeModel' : 'Happy.data.Model',

            metadata: metadata,

            idProperty: 'Id',
            fields: metadata.getDefaultTreeModelFields(),
            relation: metadata.getDefaultModelRelationConfig(),
            proxy: metadata.getDefaultTreeProxyConfig()
        };
        Ext.merge(classConfig, metadata.data.treeModel || {});
        Ext.define(metadata.getTreeModelClassName(), classConfig);
    }
});